package com.hcc.flow.server.common.utils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AesEncryptUtils {
	private static final Logger log = LoggerFactory.getLogger("adminLogger");
	private static final String KEY = "abcdef0123456789";
	private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";

	public static String base64Encode(byte[] bytes) {
		return Base64.encodeBase64String(bytes);
	}

	public static byte[] base64Decode(String base64Code) throws Exception {
		return Base64.decodeBase64(base64Code);
	}

	public static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {
		KeyGenerator kgen = KeyGenerator.getInstance("AES");
		kgen.init(128);
		Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
		cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));
		return cipher.doFinal(content.getBytes("utf-8"));
	}

	public static String aesEncrypt(String content, String encryptKey) throws Exception {
		return base64Encode(aesEncryptToBytes(content, encryptKey));
	}

	public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {
		KeyGenerator kgen = KeyGenerator.getInstance("AES");
		kgen.init(128);
		Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
		cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
		byte[] decryptBytes = cipher.doFinal(encryptBytes);
		return new String(decryptBytes, "utf-8");
	}

	public static String aesDecrypt(String encryptStr, String decryptKey) throws Exception {
		return aesDecryptByBytes(base64Decode(encryptStr), decryptKey);
	}
	
	public static String aesDecrypt(String encryptStr) throws Exception {
		return aesEncrypt(encryptStr, KEY);
	}
	
	public static void main(String[] args) throws Exception {
		String content = "好你";
		log.debug("加密前：" + content);

		String encrypt = aesEncrypt(content, KEY);
		log.debug(encrypt.length() + ":加密后：" + encrypt);

		String con = "88em998DkVqoZ2qO+352RwDIvyuRYoHX3vBWFDyBDZ4ihavnWa3fTSzLC/zyqJqEltzkoHG+VJtb83txxN1XDn649SZHFJKEfBpfynydS5VbDettPU/yE1buTkzY2L+rs2jWHz2J8euPEq6vvi5CPeniPWuduvgi2yyURP+s4FVkfQrr40dwZe0WRdbAEC0s";
		String decrypt = aesDecrypt(con, KEY);
		log.debug("解密后：" + decrypt);
	}
	

}